/* global React */
function SeasonSetupScreen() {
  const { Badge } = window.GT7LeagueDesignSystem_258437;
  const planning = window.GT7DATA.seasonPlanning;
  const helpers = window.GT7SeasonPlanning;
  const [roundSlots, setRoundSlots] = React.useState(planning.roundSlots);
  const [selectedMode, setSelectedMode] = React.useState(planning.season.setupMode);
  const [selectedBatchId, setSelectedBatchId] = React.useState(planning.batches[0].id);
  const [driverRanking, setDriverRanking] = React.useState(planning.batches[0].candidateIds.slice(0, planning.batches[0].picks));
  const [driverSubmitted, setDriverSubmitted] = React.useState(false);

  const openingBatchId = planning.batches[0].id;
  const selectedBatch = planning.batches.find((batch) => batch.id === selectedBatchId);
  const batchCandidates = planning.candidates.filter((candidate) => selectedBatch.candidateIds.includes(candidate.id));
  const recommendation = helpers.recommendBatchWinners(batchCandidates, planning.ballots, selectedBatch.picks);
  const adminOrder = helpers.getBatchAdminOrder({
    batchId: selectedBatch.id,
    openingBatchId,
    batchCandidates,
    picks: selectedBatch.picks,
    openingBatchSelectedIds: planning.adminSelectedIds,
    recommendedIds: recommendation.selectedIds,
  });
  const orderedCandidates = adminOrder
    .map((id) => batchCandidates.find((candidate) => candidate.id === id))
    .filter(Boolean);
  const warnings = helpers.getBatchBalanceWarnings(batchCandidates, adminOrder);
  const canLockBatch = orderedCandidates.length >= selectedBatch.picks;

  React.useEffect(() => {
    setDriverRanking(selectedBatch.candidateIds.slice(0, selectedBatch.picks));
    setDriverSubmitted(false);
  }, [selectedBatchId]);

  const lockCurrentBatch = () => {
    if (!canLockBatch) {
      return;
    }

    const validAdminOrder = orderedCandidates.map((candidate) => candidate.id).slice(0, selectedBatch.picks);

    if (validAdminOrder.length < selectedBatch.picks) {
      return;
    }

    setRoundSlots((slots) => helpers.lockBatch(slots, selectedBatch, validAdminOrder, batchCandidates));
  };

  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <section style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 8 }}>
            {planning.season.name}
          </div>
          <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 34, lineHeight: 1.02, color: 'var(--text-strong)' }}>
            Season Setup
          </h1>
          <p style={{ margin: '8px 0 0', fontSize: 14, color: 'var(--text-muted)', maxWidth: 760, lineHeight: 1.5 }}>
            Build the season as a hybrid board. Batch voting gives drivers input on several rounds at once while the admin keeps final control.
          </p>
        </div>
        <Badge tone="neutral">Hybrid model</Badge>
      </section>

      <section style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 10 }}>
        {planning.setupModes.map((mode) => (
          <button key={mode.id} onClick={() => setSelectedMode(mode.id)} style={{
            textAlign: 'left',
            cursor: 'pointer',
            border: `1px solid ${selectedMode === mode.id ? 'var(--accent)' : 'var(--border-subtle)'}`,
            background: selectedMode === mode.id ? 'rgba(0, 184, 255, .08)' : 'var(--surface-card)',
            borderRadius: 'var(--radius-md)',
            padding: 14,
            color: 'var(--text-body)',
          }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--text-strong)', marginBottom: 6 }}>{mode.label}</div>
            <div style={{ fontSize: 12.5, color: 'var(--text-muted)', lineHeight: 1.4 }}>{mode.description}</div>
          </button>
        ))}
      </section>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 360px), 1fr))', gap: 18, alignItems: 'start' }}>
        <SeasonBoard roundSlots={roundSlots} batches={planning.batches} onSelectBatch={setSelectedBatchId} selectedBatchId={selectedBatchId} />
        <BatchPanel
          batch={selectedBatch}
          candidates={batchCandidates}
          recommendation={recommendation}
          orderedCandidates={orderedCandidates}
          warnings={warnings}
          driverRanking={driverRanking}
          driverSubmitted={driverSubmitted}
          onMoveDriverRank={(index, direction) => setDriverRanking((ranking) => helpers.moveRank(ranking, index, direction))}
          onSubmitDriverBallot={() => setDriverSubmitted(true)}
          canLockBatch={canLockBatch}
          onLock={lockCurrentBatch}
        />
      </div>
    </div>
  );
}

function SeasonBoard({ roundSlots, batches, selectedBatchId, onSelectBatch }) {
  const { Card, Badge } = window.GT7LeagueDesignSystem_258437;
  const batchById = Object.fromEntries(batches.map((batch) => [batch.id, batch]));

  return (
    <Card style={{ display: 'grid', gap: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--text-strong)' }}>Season board</div>
        <Badge tone="caution">Draft</Badge>
      </div>
      <div style={{ display: 'grid', gap: 8 }}>
        {roundSlots.map((slot) => {
          const batch = slot.batchId ? batchById[slot.batchId] : null;
          return (
            <button key={slot.id} onClick={() => batch && onSelectBatch(batch.id)} style={{
              display: 'grid',
              gridTemplateColumns: '64px minmax(0, 1fr) auto',
              gap: 12,
              alignItems: 'center',
              textAlign: 'left',
              border: `1px solid ${slot.batchId === selectedBatchId ? 'var(--accent)' : 'var(--border-subtle)'}`,
              borderRadius: 'var(--radius-sm)',
              background: slot.status === 'locked' ? 'rgba(61, 220, 151, .08)' : 'var(--surface-raised)',
              padding: '12px 14px',
              color: 'var(--text-body)',
              cursor: batch ? 'pointer' : 'default',
            }}>
              <div style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>R{slot.roundNumber}</div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 650, color: 'var(--text-strong)' }}>
                  {slot.raceCombo ? slot.raceCombo.title : batch ? batch.title : 'Admin fixed round'}
                </div>
                <div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>{slot.targetDate} · {slot.fillMethod.replace('_', ' ')}</div>
              </div>
              <Badge tone={slot.status === 'locked' ? 'positive' : slot.status === 'voting' ? 'caution' : 'neutral'}>{slot.status}</Badge>
            </button>
          );
        })}
      </div>
    </Card>
  );
}

function BatchPanel({
  batch,
  candidates,
  recommendation,
  orderedCandidates,
  warnings,
  driverRanking,
  driverSubmitted,
  onMoveDriverRank,
  onSubmitDriverBallot,
  canLockBatch,
  onLock,
}) {
  const { Button, Card, Badge } = window.GT7LeagueDesignSystem_258437;
  return (
    <Card accent="cyan" style={{ display: 'grid', gap: 16 }}>
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--text-strong)', fontSize: 20 }}>{batch.title}</div>
        <div style={{ marginTop: 4, color: 'var(--text-muted)', fontSize: 13 }}>{batch.roundSlotIds.length} rounds · choose {batch.picks} from {candidates.length} candidates</div>
      </div>

      <div style={{ display: 'grid', gap: 8 }}>
        <PanelLabel>Recommended winners</PanelLabel>
        {recommendation.scoredCandidates.slice(0, batch.picks).map((candidate) => (
          <CandidateRow key={candidate.id} candidate={candidate} suffix={`${candidate.score} pts · ${candidate.firstChoiceVotes} first`} />
        ))}
      </div>

      <div style={{ display: 'grid', gap: 8 }}>
        <PanelLabel>Admin order to lock</PanelLabel>
        {orderedCandidates.length ? orderedCandidates.map((candidate, index) => (
          <CandidateRow key={candidate.id} candidate={candidate} prefix={`R${index + 1}`} />
        )) : <div style={{ color: 'var(--text-muted)', fontSize: 13, lineHeight: 1.4 }}>Not enough structured candidates to lock this batch yet.</div>}
      </div>

      <div style={{ display: 'grid', gap: 8 }}>
        <PanelLabel>Balance checks</PanelLabel>
        {warnings.length ? warnings.map((warning) => (
          <div key={warning.code} style={{ color: 'var(--text-muted)', fontSize: 13, lineHeight: 1.4 }}>
            <Badge tone={warning.severity === 'danger' ? 'danger' : 'caution'}>{warning.severity}</Badge>
            <span style={{ marginLeft: 8 }}>{warning.message}</span>
          </div>
        )) : <div style={{ color: 'var(--green-400)', fontSize: 13 }}>No balance warnings for this order.</div>}
      </div>

      <DriverBatchBallot
        candidates={candidates}
        batch={batch}
        ranking={driverRanking}
        submitted={driverSubmitted}
        onMove={onMoveDriverRank}
        onSubmit={onSubmitDriverBallot}
      />

      <Button variant="data" onClick={onLock} disabled={!canLockBatch}>{`Lock ${batch.title}`}</Button>
      {!canLockBatch && (
        <div style={{ color: 'var(--text-faint)', fontSize: 12.5, lineHeight: 1.4 }}>
          {`Locking stays unavailable until this batch has ${batch.picks} valid candidate selections.`}
        </div>
      )}
    </Card>
  );
}

function CandidateRow({ candidate, prefix, suffix }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr) auto', gap: 10, alignItems: 'center', padding: '10px 12px', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', background: 'var(--surface-raised)' }}>
      <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--accent)', minWidth: 24 }}>{prefix || `#${candidate.rank}`}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 650, color: 'var(--text-strong)' }}>{candidate.title}</div>
        <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{candidate.meta} · ~{candidate.durationMin} min</div>
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>{suffix || candidate.tyre}</span>
    </div>
  );
}

function DriverBatchBallot({ candidates, batch, ranking, submitted, onMove, onSubmit }) {
  const { Button, Badge } = window.GT7LeagueDesignSystem_258437;
  const byId = Object.fromEntries(candidates.map((candidate) => [candidate.id, candidate]));
  const canSubmit = batch.status === 'voting' && ranking.some((id) => byId[id]);

  return (
    <div style={{ display: 'grid', gap: 8 }}>
      <PanelLabel>Driver ballot preview</PanelLabel>
      {canSubmit ? ranking.map((id, index) => {
        const candidate = byId[id];
        if (!candidate) {
          return null;
        }

        return (
          <div key={id} style={{ display: 'grid', gridTemplateColumns: '28px minmax(0, 1fr) auto', gap: 8, alignItems: 'center', padding: '9px 10px', borderRadius: 'var(--radius-sm)', background: 'var(--surface-raised)', border: '1px solid var(--border-subtle)' }}>
            <span style={{ fontFamily: 'var(--font-display)', color: 'var(--accent)', fontWeight: 700 }}>{index + 1}</span>
            <span style={{ minWidth: 0, color: 'var(--text-body)', fontSize: 13 }}>{candidate.title}</span>
            <span style={{ display: 'flex', gap: 4 }}>
              <RankButton disabled={submitted || index === 0} onClick={() => onMove(index, -1)}>{"\u2191"}</RankButton>
              <RankButton disabled={submitted || index === ranking.length - 1} onClick={() => onMove(index, 1)}>{"\u2193"}</RankButton>
            </span>
          </div>
        );
      }) : (
        <div style={{ color: 'var(--text-muted)', fontSize: 13, lineHeight: 1.4 }}>
          This batch is not open for driver voting yet.
        </div>
      )}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
        <Badge tone={submitted ? 'positive' : 'neutral'}>{submitted ? 'Submitted' : 'Not submitted'}</Badge>
        <Button variant="secondary" size="sm" disabled={submitted || !canSubmit} onClick={onSubmit}>Submit batch ballot</Button>
      </div>
    </div>
  );
}

function RankButton({ disabled, onClick, children }) {
  return (
    <button
      type="button"
      disabled={disabled}
      onClick={onClick}
      style={{
        width: 24,
        height: 22,
        borderRadius: 'var(--radius-xs)',
        border: '1px solid var(--border-subtle)',
        background: 'var(--surface-card)',
        color: disabled ? 'var(--ink-600)' : 'var(--text-body)',
        cursor: disabled ? 'default' : 'pointer',
      }}
    >
      {children}
    </button>
  );
}

function PanelLabel({ children }) {
  return <div style={{ fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '.13em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{children}</div>;
}

window.SeasonSetupScreen = SeasonSetupScreen;
